<template>
	<a-layout id="components-layout-demo-fixed" style="position: relative">
		<a-layout-header class="header flex flex-align-center flex-pack-justify">
			<div class="logo flex">
				<div
					class="flex flex-align-center"
					v-if="!($_has('dashboard:platform') && selectRoute.path == '/dashboard/platform')"
				>
					<div v-if="systemInfo.logUrl" style="margin-right: 10px">
						<img :src="fileUrl + systemInfo.logUrl.split(';')[0]" class="logo-img" />
					</div>
					<a-dropdown v-if="orgList.length > 1">
						<div @click="(e) => e.preventDefault()" class="flex flex-align-center">
							<span class="sys-name">{{ systemInfo.sysName || systemInfo.orgName + title }}</span>
							<a-icon type="caret-down" style="margin-left: 10px" />
						</div>
						<a-menu slot="overlay" style="max-height: 400px; overflow: auto">
							<a-menu-item @click="changeOrg(item)" v-for="(item, index) in orgList" :key="index">
								<div class="flex flex-align-center">
									<div
										v-if="item.logUrl"
										style="
											height: 30px;
											width: 30px;
											border-radius: 100%;
											overflow: hidden;
											margin-right: 5px;
											background-color: #36B7AB;
										"
									>
										<img :src="fileUrl + item.logUrl.split(';')[0]" style="width: 30px" />
									</div>
									<div>{{ item.sysName || item.orgName + title }}</div>
								</div>
								<div style="color: #999; font-size: 12px">{{ item.orgName }}</div>
							</a-menu-item>
						</a-menu>
					</a-dropdown>
					<div v-else class="flex flex-align-center">
						<span class="sys-name">{{ systemInfo.sysName || systemInfo.orgName + title }}</span>
					</div>
					<div><span class="sys-name" v-if="userInfo.deptName">——{{userInfo.deptName}}</span></div>
				</div>
				<div class="mod-name flex flex-align-center">
					<img src="/img/module.png" />
					<span>{{ selectRoute ? selectRoute.meta.title : '首页' }}</span>
					<div class="topNavList">
						<a-row>
							<a-col
								:span="8"
								class="nav-item"
								@click="skipPage({ path: '/home', meta: { title: '首页' } })"
							>
								<div class="icon"><img src="/home/icon00.png" /></div>
								<span>返回首页</span>
							</a-col>
						</a-row>
					</div>
				</div>
			</div>

			<div class="right-pro flex">
				<a
					href="javascript:;"
					class="re-home flex flex-align-center"
					@click="skipPage({ path: '/home', meta: { title: '首页' } })"
				>
					<img src="/img/re-home.png" />
					<span>返回首页</span>
				</a>

				<div class="userInfo">
					<a-dropdown class="ml50" placement="bottomRight">
						<a href="javascript:;">
							<img v-if="userInfo.avatar" :src="fileUrl + userInfo.avatar.split(';')[0]" class="avatar" />
							<img v-else src="/img/avatar.png" class="avatar" />
							<span class="username">
								{{ userInfo.realName }}
								<a-icon type="down" />
							</span>
						</a>
						<a-menu slot="overlay" class="user-dropdown-menu-wrapper">
							<a-menu-item key="1">
								<router-link to="/userinfo"><span>个人信息</span></router-link>
							</a-menu-item>
							<a-menu-divider />
							<a-menu-item key="4">
								<a href="javascript:;" @click="handleLogout()"><span>退出登录</span></a>
							</a-menu-item>
						</a-menu>
					</a-dropdown>
				</div>
			</div>
		</a-layout-header>
		<a-layout-content style="position: absolute; top: 60px; left: 0; right: 0; bottom: 0">
			<div class="flex flex-v pro-grid-content flex-1" style="background-color: #f6f8fb">
				<div
					class="flex"
					:class="[
						secondMenus && secondMenus.length > 0 ? 'sys-mainWidth' : 'mainWidth',
						selectRoute.path.indexOf('dashboard') > -1 ? 'fullmainWidth' : '',
					]"
					style="margin: 0 auto; min-height: calc(100vh - 60px); height: calc(100vh - 60px)"
				>
					<div class="left-menu" v-if="secondMenus && secondMenus.length > 0">
						<a-menu v-model="secondselectKey">
							<template v-for="(item, index) in secondMenus">
								<a-sub-menu
									:key="item.name"
									:title="item.meta.title"
									v-if="item.children && item.children.length > 0"
								>
									<a-menu-item
										:key="subItem.name"
										@click="changeTabs(subItem)"
										v-for="(subItem, subIndex) in item.children"
									>
										<div class="menu-item">{{ subItem.meta.title }}</div>
									</a-menu-item>
								</a-sub-menu>
								<a-menu-item v-else :key="item.name" @click="changeTabs(item)">
									<div class="menu-item">{{ item.meta.title }}</div>
								</a-menu-item>
							</template>
						</a-menu>
					</div>
					<div class="flex-1 fullmainWidth">
						<route-view></route-view>
					</div>
				</div>
			</div>
		</a-layout-content>
	</a-layout>
</template>

<script>
import { i18nRender } from '@/locales';
import { mapState, mapActions, mapMutations } from 'vuex';
import defaultSettings from '@/config/defaultSettings';
import { updateTheme } from '@/pro-layout/utils/dynamicTheme';
import RouteView from './RouteView';
import { sysManageapi } from '@/api/index.js';
import { upLoginCache } from '@/api/index';
export default {
	name: 'BasicLayout',
	components: {
		RouteView,
	},
	data() {
		return {
			// preview.pro.antdv.com only use.
			isProPreviewSite: process.env.VUE_APP_PREVIEW === 'true' && process.env.NODE_ENV !== 'development',
			// end
			isDev: process.env.NODE_ENV === 'development' || process.env.VUE_APP_PREVIEW === 'true',

			// base
			menus: [],

			title: defaultSettings.title,
			mixTopMenu: [],
			// userInfo: {},
			fileUrl: process.env.VUE_APP_FILE_API,
			moduleTitle: '',
			secondMenus: [], //二级菜单
			secondselectKey: '',
			orgList: [], //该账户所属机构
			selectRoute: null,
			oldfullPath: '',
		};
	},
	computed: {
		...mapState({
			// 动态主路由
			mainMenu: (state) => state.permission.routers,
			activePage: (state) => state.activePage,
			userInfo: (state) => state.user.userinfo || {},
			systemInfo: (state) => state.globalOrg || {},
			deviceType: (state) => state.websockStore.deviceType,
			hostname: (state) => state.hostname,
			isPro: (state) => state.isPro,
		}),
	},
	mounted() {},
	watch: {
		activePage(newval, oldval) {
			let secondMenus = [];
			if (this.activePage) {
				let info = this.mixTopMenu.find((item) => item.name == this.activePage);
				secondMenus = info ? info.children : [];
			}
			if (secondMenus && secondMenus.length > 0) {
				//二级菜单
				this.secondMenus = secondMenus.filter((item) => !item.hidden);
				/* 过滤三级菜单 */
				this.secondMenus.forEach((item) => {
					if (item.children && item.children.length > 0) {
						item.children = item.children.filter((subitem) => !subitem.hidden);
					}
				});
			} else {
				this.secondMenus = [];
			}
			console.log('secondMenus', secondMenus);
		},
		$route: {
			handler(to, from) {
				console.log('基础布局任务列表变化：', to, from);
				if (from && to.path == from.path) {
					this.oldfullPath = from.fullPath;
				} else {
					this.oldfullPath = '';
				}
				let curPath = window.location.hash.split('#')[1];
				console.log('啥玩意' + JSON.stringify(to.name));
				let secondselectKey = this.$ls.get('secondselectKey') || '';
				this.selectRoute = { path: to.path, meta: { title: to.meta.title } };
				//特别处理
				if (to.fullPath.includes('/sysManage') || to.fullPath.includes('/doctorManage')) {
					secondselectKey = '';
				}

				this.thirdMenus = [];
				this.thirdselectKey = '';
				if (secondselectKey == 'analysis') {
					this.thirdMenus = this.getThirdMenu(this.mainMenu, secondselectKey);
					if (this.thirdMenus && this.thirdMenus.length > 0) {
						this.thirdselectKey = this.thirdMenus[0].name;
					}
				}
				if (secondselectKey) {
					this.secondselectKey = [secondselectKey];
				} else {
					secondselectKey = this.getName(this.mainMenu, curPath);
					if (!secondselectKey) {
						secondselectKey = to.name;
					}
					this.secondselectKey = [secondselectKey];
				}
				// if(secondselectKey=='workplace'){
				// 	secondselectKey
				// }
				console.log('这里secondselectKey：', secondselectKey);
				console.log('这里this.secondselectKey：', this.secondselectKey);
				this.$ls.set('secondselectKey', secondselectKey);
				if (to.path.indexOf('dashboard') > -1) {
					console.log('daozheliema', to);
					this.secondMenus = [];
				}
			},
			immediate: true, //初始化时让handler调用一下
			deep: true, // 开启深度监听
		},
	},
	created() {
		this.getAllMenu();
		this.getUserInfo();
	},
	methods: {
		...mapActions(['Logout', 'GetInfo']),
		...mapMutations(['SET_GLOBALORG']),
		i18nRender,
		//获取所有菜单
		getAllMenu() {
			/* 获取路由 */
			this.menus = [...this.mainMenu];
			this.mixTopMenu = this.mainMenu.filter((item) => !item.hidden && item.meta.title != '首页');
			/* 如果没有菜单。提示账户没有权限 */
			if (this.menus.length == 0) {
				this.$message.error('你还没有分配权限，请联系管理员');
			}
			console.log('this.mixTopMenu', this.mixTopMenu);
		},
		//获取当前菜单name
		getName(arr, path) {
			for (let i = 0; i < arr.length; i++) {
				if (arr[i].path == path) {
					return arr[i].name;
				} else if (Array.isArray(arr[i].children)) {
					const result = this.getName(arr[i].children, path);
					if (result) {
						return result;
					}
				}
			}
		},

		getUserInfo() {
			this.$postAction(this.$api.getUserInfo).then((da) => {
				let data = da.data;
				this.$ls.set('userInfo', data);
				this.GetInfo(data);
				this.getAllOrgList();
			});
		},
		//获取所有机构
		getAllOrgList() {
			this.$postAction(sysManageapi.orgUrl.getAllList).then((da) => {
				let data = da.data;
				this.orgList = [...da.data];
				// this.systemInfo = this.orgList[0];
				if (this.userInfo.userType == '06') {
					let info = this.orgList.find((item) => item.orgId == this.userInfo.orgId);
					this.SET_GLOBALORG(info || this.orgList[0]);
				} else {
					if (!this.systemInfo || Object.keys(this.systemInfo).length == 0) {
						this.SET_GLOBALORG(this.orgList[0]);
					} else {
						let info = this.orgList.find((item) => item.orgId == this.systemInfo.orgId);
						this.SET_GLOBALORG(info || this.orgList[0]);
					}
				}
			});
		},
		//布局为mixmenu时才有的头部菜单tab切换
		changTab(value) {
			this.selectkey = value;
			this.mixTopMenu.forEach((item, index) => {
				if (this.selectkey == item.name) {
					this.menus = item.children;
				}
			});
			// localStorage.setItem('selectkey', value);
		},

		//切换二级菜单
		changeTabs(item) {
			this.secondselectKey = [item.name];
			this.$ls.set('secondselectKey', item.name);
			this.$router.push(item.path);
		},
		//退出
		handleLogout() {
			let $me = this;
			this.$confirm({
				title: '你确定要退出吗？',
				content: '',
				okText: '确定',
				cancelText: '取消',
				class: 'confirmbox',
				okType: 'danger',
				onOk() {
					/* 退出，清空token就可以 */
					$me.Logout().then(() => {
						// $me.$router.push({
						// 	path: '/user/login'
						// });
						/* 刷新页面，清除tore */
						window.location.reload();
					});
				},
				onCancel() {
					console.log('Cancel');
				},
			});
		},
		//跳转模块页面
		async skipPage(item) {
			if (item.path == '/home') {
				this.$router.replace(item.path);
				//清空缓存的路由数据
				this.$store.dispatch('setView', []);
			} else {
				this.$router.push({
					name: item.name,
					params: {
						...parameter,
					},
				});
			}
		},

		//清空缓存
		clearStorage() {},

		/* 切换机构 */
		changeOrg(item) {
			upLoginCache(item.orgId).then((da) => {
				this.SET_GLOBALORG(item);
			});
		},
	},
};
</script>
<style scoped lang="less">
.mainWidth {
	width: 1440px;

	@media screen and (max-width: 1680px) {
		width: 1200px;
	}
}

.sys-mainWidth {
	width: 1600px;

	@media screen and (max-width: 1680px) {
		width: 1360px;
	}

	@media screen and (max-width: 1366px) {
		width: 1200px;
	}
}
.fullmainWidth {
	width: 100%;
}
/deep/.ant-layout {
	background: transparent !important;
}

.header {
	position: fixed;
	z-index: 999;
	width: 100%;
	background: @primary-color;
	padding: 0 25px;
	// -webkit-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
	// box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);

	ul.navs {
		margin: 0 auto;
		max-width: 1440px;
		height: 60px;
		text-align: center;
		padding-left: 0;

		li {
			float: left;
			display: inline-block;
			height: 100%;
			line-height: 60px;
			text-decoration: none;
			/* border-bottom: 3px solid transparent; */
			color: #fff;

			a {
				display: inline-block;
				height: 100%;
				line-height: 60px;
				padding: 0 20px 0 20px;
				text-decoration: none;
				font-size: 18px;
				// border-bottom: 3px solid transparent;
				color: #fff;

				&:hover {
					background: #01a8ae;
					color: #fff;
				}
			}
		}

		li a.active {
			background: #01a8ae;
			color: #fff;
		}
		&.official {
			li a.active {
				background: #5677f5;
			}
		}
	}
}

.head-menu {
	// width: 800px;
	text-align: center;
	margin: 0 auto;
	line-height: 64px;
}

.right-pro {
	.re-home {
		color: #fff;
		cursor: pointer;

		i {
			font-size: 24px;
			vertical-align: -0.22em;
		}

		img {
			width: 26px;
			height: 22px;
			// margin-top: -3px;
		}

		span {
			margin-left: 7px;
			font-size: 18px;
		}
	}

	/deep/.userInfo {
		.avatar {
			width: 28px !important;
			height: 28px !important;
			border-radius: 50%;
			// background: #fff;
			//border: 1px solid @primary-color;
			cursor: pointer;

			i {
				// color: @primary-color;
			}

			&.bg {
				//background: url('../assets/images/home/touxiang.jpg') center center no-repeat;
				background-size: 100% auto;
			}
		}

		.username {
			color: #fff;
			margin-left: 10px;
		}
	}
}

/deep/.logo {
	color: #fff;

	.logo-img {
		height: 36px;
		width: auto;
		margin-top: -3px;
	}

	.sys-name {
		color: #fff;
		font-size: 18px;
		margin-left: 7px;
	}

	.mod-name {
		color: #fff;
		margin-left: 78px;
		padding: 0 10px;
		cursor: pointer;
		position: relative;

		i {
			font-size: 24px;
			vertical-align: -0.22em;
		}

		img {
			width: 26px;
			height: 23px;
		}

		span {
			margin-left: 7px;
			font-size: 18px;
		}

		.topNavList {
			position: absolute;
			display: none;
			width: 360px;
			background-color: #fff;
			top: 60px;
			left: 0;
			z-index: 98;
			box-shadow: 0 0 40px 1px #ff000014;

			.nav-item {
				width: 100px;
				height: 100px;
				text-align: center;
				margin: 10px;
				cursor: pointer;
				transition: all 0.3s;

				&:hover {
					background-color: rgba(0, 190, 197, 0.2);
				}
				&.official {
					background-color: rgba(86, 151, 245, 0.2);
				}
				.icon {
					display: block;
					width: 40px !important;
					height: 40px !important;
					overflow: hidden;
					margin: 10px auto 0;

					img {
						width: 100%;
						height: auto;
					}
				}

				span {
					color: #383838;
				}
			}
		}

		&:hover {
			background-color: #01a8ae;
			.topNavList {
				display: block;
			}
		}
	}
}

.ml50 {
	margin-left: 50px;
}

/* 底部样式 */
/deep/.ant-layout-footer {
	padding: 0;
}

/deep/.left-menu {
	width: 160px;
	display: inline-block;
	margin: 15px 0;
	overflow: auto;

	ul {
		width: 125px;
		background-color: #fff;
		border-radius: 8px;
		margin-left: 21px;
		padding: 23px 0;
		box-shadow: 0px 4px 8px rgba(19, 29, 53, 0.02);

		li {
			display: inline-block;
			width: 100%;
			text-align: center;
			margin-bottom: 0 !important;

			.menu-item,
			.ant-menu-submenu-title {
				display: block;
				color: #2e2424;
				font-size: 16px;
				// width: 75px;
				height: 36px;
				line-height: 36px;
				border-radius: 4px;
			}

			.menu-item:hover,
			.ant-menu-submenu-title:hover {
				color: @primary-color;
			}
			&.ant-menu-item-selected {
				background-color: transparent;
			}
			&.ant-menu-item-selected .menu-item,
			&.ant-menu-submenu-selected .menu-item {
				background-color: @primary-color;
				color: #fff;
			}

			&.ant-menu-submenu-selected .ant-menu-submenu-title {
				color: @primary-color;

				.ant-menu-submenu-arrow:before,
				.ant-menu-submenu-arrow:after {
					color: @primary-color;
					background-image: linear-gradient(to right, @primary-color, @primary-color);
				}
			}
		}
		li:hover {
			&.ant-menu-item-selected .menu-item {
				background-color: @primary-color!important;
				color: #fff !important;
			}
		}
	}
}
</style>
